package com.hps.demo.config;

import com.hps.demo.serialization.ProtostuffSerializer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author heps
 * @since 2020/7/9 16:37
 */
@Configuration
@EnableCaching
public class RedisCacheConfig {

  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    // 创建一个模板类
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    // 将刚才的redis连接工厂设置到模板类中
    template.setConnectionFactory(factory);
    // 设置key的序列化器
    template.setKeySerializer(new StringRedisSerializer());

    template.setValueSerializer(new JdkSerializationRedisSerializer());

    return template;
  }

  @Bean
  public RedisTemplate<Object, Object> protoStuffTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory);

    // redis key使用的序列化器
    template.setKeySerializer(new StringRedisSerializer());

    // redis value使用的序列化器
    template.setValueSerializer(new ProtostuffSerializer());

    template.afterPropertiesSet();
    return template;
  }

  @Bean
  public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
    //初始化一个RedisCacheWriter
    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);

    RedisCacheConfiguration defaultCacheConfig=
        RedisCacheConfiguration.defaultCacheConfig()
            .serializeValuesWith(RedisSerializationContext
                .SerializationPair.fromSerializer(new ProtostuffSerializer()));
    return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
  }
}
